package servlets;

import dataObjects.*;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Transaction;


public class LoginServlet extends HttpServlet{

	public static void main(String[] args) throws Exception{
		System.out.println(getUserNames("jevans", "jevans"));
	}
  	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/xml");
        resp.getWriter().println("<response>");
        try{
        	resp.getWriter().println(getUserNames(req.getParameter("loginName"), req.getParameter("password")));
        }
        catch(Exception e){
        	resp.getWriter().println("error");
        }
        resp.getWriter().println("</response>");
    }
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/xml");
        resp.getWriter().println("<response>");
        try{
        	resp.getWriter().println(getUserNames(req.getParameter("loginName"), req.getParameter("password")));
        }
        catch(Exception e){
        	resp.getWriter().println("error");
        }
        resp.getWriter().println("</response>");
    }
	
	protected static String getUserNames(String login, String pass) throws Exception{
		Login user;// = new User("dloutschis awesome(very much so)", "Derekthankyouprees", "Evans(the chinaman");
		LoginDAO dao = new LoginDAO();
	//	HibernateSessionFactory.setConfigFile(HibernateSessionFactory.CONFIG_FILE_LOCATION_USER);
		Transaction tx = dao.getSession().beginTransaction();
		user = dao.findById(login);
		tx.commit();
		dao.getSession().close();
		if(user == null || !user.getPassword().equals(pass)) throw new Exception("No such user, or the password is incorrect");
		return user.getUsers();
	}
}